#!/usr/bin/ruby

def trim_data_to_files(f_in, folder_out)

	Dir.mkdir(folder_out) unless Dir.entries(Dir.pwd).include?(folder_out)
	f 				= File.new(f_in)
	meta_f		= File.new(folder_out + "/_meta.txt", 'w')

	# Split all of the data appart into arrays.
	dat_groups 	= f.read.split("\n\n").map {|v| v.split("\n").map {|v2| v2.split("\t")} }
	meta 			= dat_groups.shift
	genes			= dat_groups.shift.map {|g| g[1]}

	dat_groups.each do |dat|
		name 		= f_in.gsub(/\.txt$/, "")
		motif_i	= dat.shift[0][/\d.*/] 
		name 		+= motif_i + ".txt"

		f_out 	= File.open(folder_out + "/" + name, 'w')
		score		= dat.pop[0][/\d.*/]
		meta_f.write(name + "\t" + score + "\n")
		dat.pop
		
		dat.each {|seq_dat| f_out.write(">#{genes[seq_dat[1].to_i]}\n#{seq_dat[0]}\n") }
	end
end


case(ARGV.size)
when 1
	trim_data_to_files(ARGV[0], ARGV[0].gsub(/\..*/, ""))
when 2
	trim_data_to_files(ARGV[0], ARGV[1])
else
	puts "Invalid number of arguments. Aborting."
end
